//--------------------------------------------------- // Purpose: To implement the game "keep away chess" // using 2D arrays and functions. // Authors: John Gauch //--------------------------------------------------- #include using namespace std; // Program constants const int ROWS = 8; const int COLS = 8; //--------------------------------------------------- // Print the 2D game board //--------------------------------------------------- void print_board(char board[ROWS][COLS]) { // Print values cout << " "; for (int col = 0; col < COLS; col++) cout << col << " "; cout << endl; // Print line cout << " +"; for (int col = 0; col < COLS; col++) cout << "---+"; cout << "\n"; // Print board for (int row = 0; row < ROWS; row++) { // Print values cout << " " << row << " | "; for (int col = 0; col < COLS; col++) cout << board[row][col] << " | "; cout << endl; // Print line cout << " +"; for (int col = 0; col < COLS; col++) cout << "---+"; cout << "\n"; } } //--------------------------------------------------- // Check rows and columns for another chess piece //--------------------------------------------------- bool check_board(char board[ROWS][COLS], const int my_row, const int my_col) { bool safe = true; // Check row for (int col = 0; col < COLS; col++) if (board[my_row][col] != ' ') safe = false; // Check column for (int row = 0; row < ROWS; row++) if (board[row][my_col] != ' ') safe = false; // Check diagonals (long slow way) for (int count = 0; count < ROWS; count++) { if ((my_row+count < ROWS) && (my_col+count < COLS)) if (board[my_row+count][my_col+count] != ' ') safe = false; if ((my_row+count < ROWS) && (my_col-count >= 0)) if (board[my_row+count][my_col-count] != ' ') safe = false; if ((my_row-count >= 0) && (my_col+count < COLS)) if (board[my_row-count][my_col+count] != ' ') safe = false; if ((my_row-count >= 0) && (my_col-count >= 0)) if (board[my_row-count][my_col-count] != ' ') safe = false; } // Check diagonals (short slow way) for (int row = 0; row < ROWS; row++) for (int col = 0; col < COLS; col++) if (row+col == my_row+my_col || row-col == my_row-my_col) if (board[row][col] != ' ') safe = false; // Return result return safe; } //--------------------------------------------------- // Main program //--------------------------------------------------- int main() { // Define game board char board[ROWS][COLS]; for (int row = 0; row < ROWS; row++) for (int col = 0; col < COLS; col++) board[row][col] = ' '; // Print game board print_board(board); // Loop playing game bool safe = true; while (safe) { // Get user input cout << "Enter row and col: "; int my_row, my_col; cin >> my_row >> my_col; // Put queen on board safe = check_board(board, my_row, my_col); if (safe) board[my_row][my_col] = 'Q'; else board[my_row][my_col] = 'X'; // Print game board print_board(board); } return 0; }